/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Redias Library App for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.libraryapp;

import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import dk.redia.lib.log.Log;
import dk.redia.lib.utils.AppApplication;
import dk.redia.lib.utils.AppConfiguration;
import dk.redia.lib.xmlrpc.XmlRpcClientResultListener;
import dk.redia.lib.xmlrpc.XmlRpcResultDumper;
import dk.redia.lib.xmlrpc.XmlRpcResultUtils;
import dk.redia.libraryapp.authentication.Authentication;
import dk.redia.libraryapp.model.Reservation;
import dk.redia.libraryapp.xmlrpc.library.XmlRpcClient;

public class ReservationResultActivity extends Activity {

	public static final String EXTRAS_KEY_RESERVATION = "reservation";

	private static final int DIALOG_MISSING_PREFERRED_BRANCH = 1;
	private static final String logTag = "ReservationResultActivity";

	private Reservation reservation;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    // Only proceed with reservation, if there is a preferred
	    // libary branch to deliver the materials to
	    if (Authentication.getInstance().getPreferredBranch()==null || Authentication.getInstance().getPreferredBranch()=="") {
	    	showDialog(DIALOG_MISSING_PREFERRED_BRANCH);
	    	return;
	    }
	    
	    setContentView(R.layout.reservationresult);
	    String preferredBranchName = Authentication.getInstance().getPreferredBranchName();
	    if (preferredBranchName == null || preferredBranchName.compareTo("") == 0) {
	    	preferredBranchName = getString(R.string.unknown);
	    }
	    String branchNameText = getString(R.string.reservationResultForPickupAtText) + " " + preferredBranchName;
	    TextView branchTextView = (TextView)findViewById(R.id.reservationResultPickupBranchStaticTextView);
	    TextView titleTextView = (TextView)findViewById(R.id.reservationResultTitleTextView);

	    Intent i = getIntent();
	    Bundle b = i.getExtras();
	    assert(b != null);
	    
	    reservation = (Reservation)b.get(EXTRAS_KEY_RESERVATION);
	    assert(reservation != null);
	    
	    branchTextView.setText(branchNameText);
	    titleTextView.setText(reservation.getTitle());
	}
	
	protected Dialog onCreateDialog(int dialogId) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		String text = getString(R.string.unableToReserveDueToMissingPreferredBranchText);
    	text = text.replace("$URL$", getString(R.string.websiteUrl));
		builder.setMessage(text);
		builder.setCancelable(false);
		builder.setPositiveButton(R.string.okButtonText, new OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setData(Uri.parse("http://" + getString(R.string.websiteUrl)));
				startActivity(i);
				finish();
			}
		});
		return builder.create();
	}
	
	public void onOkButtonClicked(final View v) {
		Log.d(logTag, "Reserving item with reservation id " + reservation.getReservationId());
		final ProgressBar progressBar = (ProgressBar)findViewById(R.id.reservationResultProgressBar);
		final Button cancelButton = (Button)findViewById(R.id.reservationResultCancelButton);
		
		cancelButton.setEnabled(false);
		v.setEnabled(false);
		progressBar.setVisibility(View.VISIBLE);
		
		XmlRpcClient.getInstance().addReservation(
				AppConfiguration.getInstance().getCustomerId(), 
				AppConfiguration.getInstance().getApiKey(), 
				reservation.getReservationId(), 
				Authentication.getInstance().getPreferredBranch(), 
				new XmlRpcClientResultListener() {
			
			public void callFailed(String message) {
				Log.e(logTag, "Failed to reserve item: " + message);
				cancelButton.setEnabled(true);
				v.setEnabled(true);
				progressBar.setVisibility(View.GONE);
				AppApplication.toast(R.string.failedToReserveText, Toast.LENGTH_LONG);
			}
			
			public void callCompleted(Object resultObj) {
				XmlRpcResultDumper.dump(resultObj);
				Map<String, Object> result = XmlRpcResultUtils.unpackStandardResult(resultObj);
				Boolean b = (Boolean)result.get("result");
				String message = (String)result.get("message");
				cancelButton.setEnabled(true);
				v.setEnabled(true);
				progressBar.setVisibility(View.GONE);
				if (b) {
					AppApplication.toast(R.string.successfullyReservedText, Toast.LENGTH_LONG);
					finish();
				} else {
					Log.e(logTag, "Failed to reserve material with id " + reservation.getReservationId() + " and title " + reservation.getTitle() + ": " + message);
					AppApplication.toast(R.string.failedToReserveText, Toast.LENGTH_LONG);
				}
			}
		});
		
	}
	
	public void onCancelButtonClicked(View v) {
		finish();
	}

}
